# -*- coding: utf-8 -*-
# @Time    : 2024/11/10 14:23
# @Author  : CHNJX
# @File    : api_utils.py
# @Desc    :

from flask import current_app
import json
from datetime import datetime


def log_operation(operation_type, resource_type, resource_id, user_id=None, details=None):
    """记录操作日志"""
    log_entry = {
        'operation_type': operation_type,  # 如：CREATE, UPDATE, DELETE
        'resource_type': resource_type,  # 如：Device, Module, TestCase
        'resource_id': resource_id,
        'user_id': user_id,
        'details': details,
        'timestamp': datetime.utcnow().isoformat()
    }

    current_app.logger.info(f'Operation Log: {json.dumps(log_entry)}')
    return log_entry


def validate_data(data, required_fields):
    """验证请求数据"""
    if not data:
        return False, "请求数据不能为空"

    missing_fields = [field for field in required_fields if field not in data]
    if missing_fields:
        return False, f"缺少必要的字段: {', '.join(missing_fields)}"

    return True, None


def paginate_query(query, page=1, per_page=20):
    """查询结果分页"""
    try:
        page = int(page)
        per_page = int(per_page)
    except (TypeError, ValueError):
        page = 1
        per_page = 20

    # 确保合理的分页参数
    page = max(1, page)
    per_page = max(1, min(100, per_page))

    # 执行分页查询
    pagination = query.paginate(page=page, per_page=per_page, error_out=False)

    return {
        'items': pagination.items,
        'total': pagination.total,
        'page': page,
        'per_page': per_page,
        'pages': pagination.pages
    }


def build_search_filter(model, search_term, searchable_fields):
    """构建搜索过滤器"""
    from sqlalchemy import or_

    if not search_term or not searchable_fields:
        return None

    filters = []
    for field in searchable_fields:
        if hasattr(model, field):
            filters.append(getattr(model, field).ilike(f'%{search_term}%'))

    return or_(*filters) if filters else None


class APIException(Exception):
    """API异常基类"""

    def __init__(self, message, code=400, data=None):
        super().__init__()
        self.message = message
        self.code = code
        self.data = data


def handle_api_exception(error):
    """处理API异常"""
    response = {
        'code': error.code,
        'message': error.message,
        'data': error.data
    }
    return response, error.code